<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb
      separator-class="el-icon-arrow-right"
      style="font-size: 15px"
    >
      <el-breadcrumb-item>当前位置：订单管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- <audio ref="audioTip" muted :src="auto.src"></audio> -->
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="9">
          <el-tabs v-model="queryInfo2.state" @tab-click="handleClick">
            <el-tab-pane label="全部订单" name="0"></el-tab-pane>
            <el-tab-pane label="未支付" name="1"></el-tab-pane>
            <el-tab-pane label="待接单" name="2"></el-tab-pane>
            <el-tab-pane label="进行中" name="3"></el-tab-pane>
            <el-tab-pane label="可取餐" name="4"></el-tab-pane>
            <el-tab-pane label="已完成" name="5"></el-tab-pane>
          </el-tabs>
        </el-col>
        <el-col :span="2" :offset="1">
          <el-date-picker
            v-model="date"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="dateChange"
            value-format="yyyy-MM-dd HH:mm:ss"
          >
          </el-date-picker>
        </el-col>
        <el-col :span="7" :offset="5">
          <el-input
            placeholder="请输入手机号"
            v-model="queryPhone"
            class="input-with-select"
            clearable
            @clear="clearInput"
          >
            <el-select
              style="width: 110px"
              v-model="queryType"
              slot="prepend"
              placeholder="请选择"
            >
              <el-option label="全部商品" value="0"></el-option>
              <el-option label="奶茶" value="1"></el-option>
              <el-option label="宠物商品" value="2"></el-option>
            </el-select>
            <el-button
              class="button"
              slot="append"
              icon="el-icon-search"
              @click="getOrderListWithPN(1)"
            ></el-button>
          </el-input>
        </el-col>
      </el-row>

      <!-- 订单列表区域 -->
      <el-table :data="orderList" border stripe>
        <el-table-column
          label="订单号"
          prop="number"
          min-width="10%"
        ></el-table-column>
        <el-table-column
          label="购买人"
          prop="userName"
          min-width="10%"
        ></el-table-column>
        <el-table-column
          label="收货人"
          prop="addressName"
          min-width="10%"
        ></el-table-column>
        <el-table-column
          label="手机号"
          prop="phone"
          min-width="10%"
        ></el-table-column>
        <el-table-column
          label="配送类型"
          prop="distribution_type"
          min-width="8%"
        >
          <template slot-scope="scope">
            <el-tag
              :type="
                scope.row.distribution_type === '配送' ? '#409EFF' : 'success'
              "
              disable-transitions
              >{{ scope.row.distribution_type }}</el-tag
            >
          </template>
        </el-table-column>

        <el-table-column
          label="订单商品"
          prop="commodity_type"
          min-width="10%"
        ></el-table-column>
        <el-table-column label="总价" prop="total" min-width="7%">
          <template slot-scope="scope">
            {{ scope.row.total / 100 }}元
          </template>
        </el-table-column>

        <el-table-column
          label="取件码"
          prop="code"
          min-width="7%"
        ></el-table-column>
        <el-table-column label="订单状态" prop="state" min-width="8%">
          <template slot-scope="scope">
            <el-tag
              :type="
                scope.row.state === '未支付'
                  ? 'danger'
                  : scope.row.state === '待接单'
                  ? 'info'
                  : scope.row.state === '进行中'
                  ? '#409EFF'
                  : scope.row.state === '可取餐'
                  ? 'warning'
                  : 'success'
              "
              disable-transitions
              >{{ scope.row.state }}</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column
          label="下单时间"
          prop="data"
          min-width="10%"
        ></el-table-column>
        <el-table-column label="用户信息" min-width="9%" v-if="sureAdmin">
          <template slot-scope="scope">
            <!-- 详情按钮 -->
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-more"
              @click="toUserInfo(scope.row.userId)"
            ></el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="15%">
          <template slot-scope="scope">
            <!-- 详情按钮 -->
            <el-button
              type="primary"
              size="mini"
              @click="toMoreOrder(scope.row.id)"
              >详情</el-button
            >
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.id)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo2.pageNo"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo2.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!-- 修改订单状态的对话框 -->
    <el-dialog
      title="修改订单状态"
      :visible.sync="editDialogVisible"
      width="500px"
      @close="editDialogClosed"
    >
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="180px"
      >
        <el-form-item class="textLeft" label="订单单号：">{{ editInfo.number }}</el-form-item>
        <el-form-item class="textLeft" label="下单人：">{{ editInfo.userName }}</el-form-item>
        <el-form-item class="textLeft" label="收货人：">{{ editInfo.addressName }}</el-form-item>
        <el-form-item class="textLeft" label="手机号：">{{ editInfo.phone }}</el-form-item>
        <el-form-item class="textLeft" label="订单商品：">{{
          editInfo.commodity_type
        }}</el-form-item>
        <el-form-item class="textLeft" label="价格：">{{ editInfo.total / 100 }}</el-form-item>
        <el-form-item class="textLeft" label="订单状态：">
          <el-select
            v-model="editForm.stateId"
            placeholder="请选择"
            value-key="id"
          >
            <el-option
              v-for="item in stateList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //默认为全部订单
      // activeName: "0",
      // 获取订单列表的参数对象
      // queryInfo: {
      //   // 当前的页数
      //   pageNo: 1,
      //   // 当前每页显示多少条数据
      //   pageSize: 10,
      //   stateId: 0,
      // },
      queryInfo2: {
        // 当前的页数
        pageNo: 1,
        // 当前每页显示多少条数据
        pageSize: 10,
        //默认全部订单
        state: "0",
        //默认全部商品
        type: "0",
        phone: "",
        startTime: undefined,
        endTime: undefined,
      },
      queryPhone: "",
      queryType: "0",
      date: "",
      total: 0,
      orderList: [],
      editInfo: {},
      editForm: {
        stateId: 1,
      },
      stateList: [],
      editDialogVisible: false,
      editFormRules: {
        // 验证表单是否合法
        name: [
          { required: true, message: "请输入商品分类名称", trigger: "blur" },
        ],
      },
      // date:"",
      // phoneInput: "",
      // select: "1",
      sureAdmin: false,
    };
  },
  created() {
    var Admin = window.localStorage.getItem("admin");
    if (Admin == 1) {
      this.sureAdmin = true;
    } else {
      this.sureAdmin = false;
    }
    this.getOrderList();
    window.localStorage.removeItem("lastOrder");
  },
  mounted() {
    if (this.timer) {
      clearInterval(this.timer);
    } else {
      this.timer = setInterval(() => {
          this.getOrderList();
      }, 5000);
    }
  },
  destroyed() {
    clearInterval(this.timer);
  },
  // 监听异常发生变化，语音播报
  watch: {
    // newOrder: function (newVal, oldVal) {
    //   console.log("变化了");
    //   console.log(newVal, oldVal);
    //   if (newVal > oldVal) {
    //     this.aplayAudio();
    //   }
    // },
  },
  methods: {
    dateChange() {
      console.log("xxxxxxxxxxxxxxxx", this.date);
    },
    clearInput() {
      // this.queryInfo2.phone = this.queryPhone;
      this.getOrderListWithPN(1);
    },
    async getOrderList() {
      // if (this.activeName === "1") {
      //   const { data: res } = await this.$http.get("order/listOrder", {
      //     params: this.queryInfo,
      //   });
      //   console.log(res);
      //   if (res.code !== 200) {
      //     return this.$message.error("获取订单列表失败！");
      //   }
      //   this.orderList = res.data.orderVOS;
      //   this.total = res.data.count;
      // }
      // if (this.activeName === "2") {
      //   this.queryInfo.stateId = 1;
      //   const { data: res } = await this.$http.get("order/listOrderByState", {
      //     params: this.queryInfo,
      //   });
      //   console.log(res);
      //   if (res.code !== 200) {
      //     return this.$message.error("获取订单列表失败！");
      //   }
      //   this.orderList = res.data.orderVOS;
      //   this.total = res.data.count;
      // }
      // if (this.activeName === "3") {
      //   this.queryInfo.stateId = 2;
      //   const { data: res } = await this.$http.get("order/listOrderByState", {
      //     params: this.queryInfo,
      //   });
      //   console.log(res);
      //   if (res.code !== 200) {
      //     return this.$message.error("获取订单列表失败！");
      //   }
      //   this.orderList = res.data.orderVOS;
      //   this.total = res.data.count;
      // }
      // if (this.activeName === "4") {
      //   this.queryInfo.stateId = 3;
      //   const { data: res } = await this.$http.get("order/listOrderByState", {
      //     params: this.queryInfo,
      //   });
      //   console.log(res);
      //   if (res.code !== 200) {
      //     return this.$message.error("获取订单列表失败！");
      //   }
      //   this.orderList = res.data.orderVOS;
      //   this.total = res.data.count;
      // }
      // if (this.activeName === "5") {
      //   this.queryInfo.stateId = 4;
      //   const { data: res } = await this.$http.get("order/listOrderByState", {
      //     params: this.queryInfo,
      //   });
      //   console.log(res);
      // if (res.code !== 200) {
      //   return this.$message.error("获取订单列表失败！");
      // }
      // this.orderList = res.data.orderVOS;
      // this.total = res.data.count;
      // }
      // if (this.activeName === "6") {
      //   this.queryInfo.stateId = 5;
      //   const { data: res } = await this.$http.get("order/listOrderByState", {
      //     params: this.queryInfo,
      //   });
      //   console.log(res);
      //   if (res.code !== 200) {
      //     return this.$message.error("获取订单列表失败！");
      //   }
      //   this.orderList = res.data.orderVOS;
      //   this.total = res.data.count;
      // }
      const { data: res } = await this.$http.get("order/listOrderLikeAll", {
        params: this.queryInfo2,
      });
      console.log(this.queryInfo2);
      console.log(res);
      if (res.code !== 200) {
        return this.$message.error("获取订单列表失败！");
      }
      this.orderList = res.data.ord;
      this.total = res.data.count;
    },
    getOrderListWithPN(pageNum) {
      // if (
      //   this.queryInfo2.phone != "" ||
      //   this.queryInfo2.startTime != undefined ||
      //   this.queryInfo2.endTime != undefined ||
      //   this.queryInfo2.type != "0"
      // ) {
      // }
      this.queryInfo2.pageNo = pageNum;
      this.queryInfo2.type = this.queryType;
      this.queryInfo2.phone = this.queryPhone;
      //判断this.date是否为null
      if (!this.date && typeof(this.date)!="undefined" && this.date!=0) {
        // this.queryInfo2.startTime = this.date[0];
        // this.queryInfo2.endTime = this.date[1];
        this.queryInfo2.startTime = undefined;
        this.queryInfo2.endTime = undefined;
      }else{
        // this.queryInfo2.startTime = undefined;
        // this.queryInfo2.endTime = undefined;
        this.queryInfo2.startTime = this.date[0];
        this.queryInfo2.endTime = this.date[1];
      }

      console.log(this.queryInfo2.startTime, "xxxxx");
      this.getOrderList();
    },
    handleClick() {
      console.log(this.activeName);
      this.getOrderListWithPN(1);
      // this.getOrderList();
    },
    // 监听 pagesize 改变的事件
    handleSizeChange(newSize) {
      // console.log(newSize)
      this.queryInfo2.pageSize = newSize;
      // if (this.query === "") {
      //   this.getOrderList();
      // } else {
      //   this.getOrderListByNumber(this.queryInfo.pageNo);
      // }
      this.getOrderList();
    },
    // 监听 页码值 改变的事件
    handleCurrentChange(newPage) {
      console.log(newPage);
      this.queryInfo2.pageNo = newPage;
      // if (this.query === "") {
      //   this.getOrderList();
      // } else {
      //   this.getOrderListByNumber(this.queryInfo.pageNo);
      // }
      this.getOrderList();
    },
    toMoreOrder(id) {
      console.log(id);
      this.$router.push("/order/moreOrder/" + id);
    },
    toUserInfo(id) {
      this.$router.push("/order/orderUser/" + id);
    },
    async showEditDialog(id) {
      console.log(id);
      const { data: res } = await this.$http.get("order/getOrderById?id=" + id);

      if (res.code !== 200) {
        return this.$message.error("查询订单信息失败！");
      }
      const { data: res2 } = await this.$http.get("order/listOrderState");
      if (res2.code !== 200) {
        return this.$message.error("查询状态失败！");
      }
      this.stateList = res2.data.orderStatuses;
      this.editForm.id = res.data.order.id;
      this.editForm.stateId = res.data.order.stateId / 1;
      this.editInfo = res.data.order;

      this.editDialogVisible = true;
    },
    // 监听修改订单状态对话框的关闭事件
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },
    // 修改订单状态信息并提交
    editUserInfo() {
      console.log(this.editForm, "=========================");
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return;
        let params = new FormData();
        params.append("id", this.editForm.id);
        params.append("stateId", this.editForm.stateId);
        // 发起修改订单状态信息的数据请求
        const { data: res } = await this.$http.post(
          "order/updateOrder",
          params
        );

        if (res.code !== 200) {
          return this.$message.error(res.massage);
        }

        // 关闭对话框
        this.editDialogVisible = false;
        // 刷新数据列表
        this.getOrderList();
        // 提示修改成功
        this.$message.success("修改订单状态成功！");
      });
    },
  },
};
</script>

<style lang="less" scoped>
.button:hover {
  background-color: rgb(64, 158, 255);
  color: rgb(255, 255, 255);
}
.el-select .el-input {
  width: 130px;
}
.input-with-select .el-input-group__prepend {
  background-color: #fff;
}
.textLeft{
  text-align: left;
}
</style>
